function getValidateHeader() {
    return  {
        'ApiKey': localStorage.getItem('user_id') + '$$' + localStorage.getItem('access_token') + '$$' + localStorage.getItem('platform') + '$$' + localStorage.getItem('platform_user_id')
    }
}

class PublicValidate {
    constructor(api) {
        this.api = api
    }

    async validate() {
        window.qcLoading.show()
        const accessToken = localStorage.getItem('access_token')
        if (!accessToken) {
            window.qcLoading.hide()
            window.qcNotify.create({
                message: '请先登录',
                color: 'negative',
                position: 'top',
                timeout: 3000,
                icon: 'error'
            })
            return null
        }
        try {
            const response = await this.api.get('/api/v1/validate', {
                headers: getValidateHeader()
            })
            const userInfo = response.data
            localStorage.setItem('user_id', userInfo.id)
            localStorage.setItem('access_token', userInfo.token)
            localStorage.setItem('platform', userInfo.platform)
            localStorage.setItem('platform_user_id', userInfo.platform_user_id)
            return userInfo
        } catch (error) {
            console.error('验证失败:', error)
            let errorMsg = '验证失败，请重试'
            if (error && error.response && error.response.data) {
                if (error.response.data.error) {
                    errorMsg = error.response.data.error
                } else if (error.response.data.message) {
                    errorMsg = error.response.data.message
                }
            }
            window.qcNotify.create({
                message: errorMsg,
                color: 'negative',
                position: 'top',
                timeout: 3000,
                icon: 'error'
            })
            return null
        } finally {
            window.qClient.client.loading.hide()
        }
    }

    async registerByMSAL() {
        window.qcLoading.show()
        const accessToken = localStorage.getItem('access_token')
        if (!accessToken) {
            window.qcLoading.hide()
            window.qcNotify.create({
                message: '请先登录',
                color: 'negative',
                position: 'top',
                timeout: 3000,
                icon: 'error'
            })
            return null
        }
        localStorage.setItem('platform', 'microsoft')
        try {
            const response = await this.api.post('/api/v1/validate', {}, {
                headers: getValidateHeader()
            })
            const userInfo = response.data
            localStorage.setItem('user_id', userInfo.id)
            localStorage.setItem('access_token', userInfo.token)
            localStorage.setItem('platform', userInfo.platform)
            localStorage.setItem('platform_user_id', userInfo.platform_user_id)
            return userInfo
        } catch (error) {
            console.error('验证失败:', error)
            let errorMsg = '验证失败，请重试'
            if (error && error.response && error.response.data) {
                if (error.response.data.error) {
                    errorMsg = error.response.data.error
                } else if (error.response.data.message) {
                    errorMsg = error.response.data.message
                }
            }
            window.qcNotify.create({
                message: errorMsg,
                color: 'negative',
                position: 'top',
                timeout: 3000,
                icon: 'error'
            })
            return null
        } finally {
            window.qcLoading.hide()
        }
    }

    redirectTo(url) {
        const loginData = {
            user_id: localStorage.getItem('user_id'),
            access_token: localStorage.getItem('access_token'),
            platform: localStorage.getItem('platform'),
            platform_user_id: localStorage.getItem('platform_user_id')
        }
        const LoginDataJSON = JSON.stringify(loginData);
        const LoginDataBase64 = btoa(
            encodeURIComponent(LoginDataJSON).replace(
              /%([0-9A-F]{2})/g,
              (match, p1) => String.fromCharCode(parseInt(p1, 16))
            )
        )
        // 作为查询参数加入LoginData，考虑url可能已有其它参数
        const targetUrl = new URL(url, window.location.origin)
        targetUrl.searchParams.set('LoginData', LoginDataBase64)
        window.location.href = targetUrl.toString()
    }
}

window.PublicValidate = PublicValidate
